package com.magicborrow.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.activity.SearchActivity;
import com.magicborrow.adapter.SearchResultFilterAdapter;
import com.magicborrow.beans.HomeHeadBean;
import com.magicborrow.beans.StuffBean;
import com.magicborrow.beans.StuffListBean;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.views.LoadingDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SearchResultFilterFragment extends Fragment implements VolleyTool.HTTPListener {

    private LinearLayout mFragmentLayout;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRefreshRecyclerView;
    private View mFootView;
    private LinearLayoutManager mLinearLayoutManager;
    private SearchResultFilterAdapter mSearchResultFilterAdapter;
    private ArrayList<StuffBean> mData;
    private int page = 0;
    private int size = 10;
    private boolean lastPage = false;
    private PopupMenu popupMenu;
    private CheckBox cb;
    private Menu menu;
    private int type;
    private LoadingDialog dialog;
    private double lon;
    private double lat;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mFragmentLayout = (LinearLayout) inflater.inflate(R.layout.search_result_filter_fragment, null);
        initView();
        SearchActivity searchActivity = (SearchActivity) getActivity();
        if (!TextUtils.isEmpty(searchActivity.content)) {
            key = searchActivity.content;

        }
        initData();
        initListener();
        searchResult();

        LocationClient mLocClient = new LocationClient(getContext());
        mLocClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                lon = bdLocation.getLongitude();
                lat = bdLocation.getLatitude();
            }
        });
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setIsNeedLocationPoiList(true);
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);
        //option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        return mFragmentLayout;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    public void onRefresh(String content) {
        key = content;
        page = 0;
        searchResult();
    }

    private void initView() {
        mSwipeRefreshLayout = (SwipeRefreshLayout) mFragmentLayout.findViewById(R.id.swipeRefreshLayout);
        mRefreshRecyclerView = (RecyclerView) mFragmentLayout.findViewById(R.id.recyclerView);
        mLinearLayoutManager = new LinearLayoutManager(getActivity());
        mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        cb = (CheckBox) mFragmentLayout.findViewById(R.id.cb_paixu);
        mRefreshRecyclerView.setLayoutManager(mLinearLayoutManager);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.title_color,
                R.color.title_color, R.color.title_color,
                R.color.title_color);
        popupMenu = new PopupMenu(getContext(), cb);
        menu = popupMenu.getMenu();
        MenuInflater menuInflater = getActivity().getMenuInflater();
        menuInflater.inflate(R.menu.menu_search, menu);
        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb.isChecked()) {
                    popupMenu.show();
                }
            }
        });
        mFragmentLayout.findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLinearLayoutManager.smoothScrollToPosition(mRefreshRecyclerView, null, 0);
            }
        });
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.search_xinyong:

                        type = 1;
                        break;
                    case R.id.search_zonghe:
                        type = 0;

                        break;
                    case R.id.search_zuigao:
                        type = 2;
                        break;
                    case R.id.zuiduo:
                        type = 3;

                        break;
                    case R.id.zuijin:
                        type = 4;

                        break;
                }
                cb.setText(item.getTitle());
                page = 0;
                if (dialog == null) dialog = new LoadingDialog(getContext());
                dialog.show();
                searchResult();
                popupMenu.dismiss();
                return false;
            }
        });
        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
            @Override
            public void onDismiss(PopupMenu menu) {
                cb.setChecked(false);
            }
        });
    }

    private void initListener() {
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
        mRefreshRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && mLinearLayoutManager.findLastVisibleItemPosition() + 1 == mSearchResultFilterAdapter.getItemCount()) {
                    if (lastPage) {
                        return;
                    }
                    showFootview(true);
                    page++;
                    searchResult();
                }
            }
        });
    }

    private String key = " ";

    private void initData() {
        mData = new ArrayList<>();
        mSearchResultFilterAdapter = new SearchResultFilterAdapter(getActivity());
        mSearchResultFilterAdapter.setData(mData);
        mRefreshRecyclerView.setAdapter(mSearchResultFilterAdapter);
    }

    private void searchResult() {
        Map<String, String> params = new HashMap<>();
        params.put("page", page + "");
        params.put("size", size + "");
        params.put("kw", key);
        params.put("type", type + "");
        params.put("lon", lon + "");
        params.put("lat", lat + "");

        VolleyTool.get(Constants.SEARCH_URL, params, this, 0, StuffListBean.class);
    }

    private void showFootview(boolean isVis) {
        if (mFootView == null) {
            mFootView = mRefreshRecyclerView.findViewWithTag("foot");
        }
        TextView tv = (TextView) mFootView.findViewById(R.id.no_more_textView);
        ProgressBar bar = (ProgressBar) mFootView.findViewById(R.id.load_more_progressBar);
        if (isVis) {
            bar.setVisibility(View.VISIBLE);
            tv.setText("正在加载...");
        } else {
            bar.setVisibility(View.GONE);
            tv.setText("没有更多了");
        }
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if (dialog != null)
            dialog.dismiss();
        if (requestCode == 0) {
            StuffListBean bean = (StuffListBean) t;
            if (bean.getCode() == 0) {
                if (page == 0) {
                    if (mSwipeRefreshLayout.isShown()) {
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                    mSearchResultFilterAdapter.getData().clear();
                    mData.addAll(bean.getData().getContent());
                    mSearchResultFilterAdapter.notifyDataSetChanged();
                    if (bean.getData().getContent().size() < 10) {
                        showFootview(false);
                    }
                } else {
                    if (bean.getData().getContent().size() > 0) {
                        int startPosition = mSearchResultFilterAdapter.getItemCount();
                        mSearchResultFilterAdapter.getData().addAll(bean.getData().getContent());
                        mSearchResultFilterAdapter.notifyItemRangeInserted(startPosition, bean.getData().getContent().size());
                    } else {
                        lastPage = true;
                        showFootview(false);
                    }
                }
            } else {
                Toast.makeText(getActivity(), bean.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {
        if (dialog != null)
            dialog.dismiss();
        Toast.makeText(getActivity(), "服务器忙", Toast.LENGTH_SHORT).show();
    }
}
